package cn.sanli.manage.controller;


import cn.sanli.manage.ex.ServiceException;
import cn.sanli.manage.web.JsonResult;
import cn.sanli.manage.web.ServiceCode;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author wzy
 * @Date 2023/11/30 15:02
 * @Description: excel相关控制器
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/excel")
@Api(tags = "excel文件相关接口")
public class ExcelController {

    @Value("${excel.path}")
    private String path;

    @Value("${excel.name}")
    private String name;

    // TODO 获取数据
//    @Resource
//    private WorkSheetService workSheetService;


    /**
     * 模版上传功能
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("模版上传功能")
    public JsonResult<?> upload(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        if(originalFilename == null) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "获取文件名失败");
        }
        log.debug("获取到文件名: {}", originalFilename);
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.debug("获取到的后缀名: {}", suffix);
        String fileName = name + suffix;
        log.debug("最终文件名: {}", fileName);
        File file = new File(path + fileName);
        log.debug("判断文件是否存在......................");
        if (!file.exists()) {
            log.debug("目标文件不存在, 开始创建文件");
            file.mkdirs();
        }
        log.debug("文件已存在, 先删除原先文件");
        boolean delete = file.delete();
        if(!delete) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "上传失败");
        }
        try {
            log.debug("开始存储文件:{}", file);
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "添加模版失败");
        }
        return JsonResult.ok();
    }

    // TODO 模版导出功能

    /**
     * 模版导出
     * @param request 请求
     * @return excel模版
     */
    @GetMapping("/educe")
    @ApiOperation("模版导出功能")
    public JsonResult educe(HttpServletRequest request) {
        String localAddr = request.getLocalAddr();
        int port = request.getServerPort();
        String excelUrl = "http://" + localAddr + ":" + port
                + "/static/excel/" + name + ".xls";

        return JsonResult.ok(excelUrl);
    }




}
